#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <pthread.h>
#include "lvgl/lvgl.h"
#include "interface_display.h"

// TCP服务器配置
#define SERVER_IP "192.168.64.182" // Ubuntu服务器IP
#define SERVER_PORT 60000
#define BUFFER_SIZE 1024

// 全局变量
static volatile int running = 1;
static int socket_fd        = -1;
static pthread_t tcp_thread;
static pthread_mutex_t data_mutex = PTHREAD_MUTEX_INITIALIZER;

// 全局停车场数据
static parking_data_t parking_data = {.total_spaces     = 500,
                                      .available_spaces = 325,
                                      .occupied_spaces  = 175,
                                      .temperature      = 25,
                                      .humidity         = 60,
                                      .light_level      = 450,
                                      .vehicles_in      = 1245,
                                      .vehicles_out     = 1198,
                                      .timestamp        = 0};

// UI更新回调函数指针
typedef void (*ui_update_callback_t)(parking_data_t * data);
static ui_update_callback_t ui_update_callback = NULL;

// 注册UI更新回调
void register_ui_update_callback(ui_update_callback_t callback)
{
    ui_update_callback = callback;
}

// 获取停车场数据（线程安全）
void get_parking_data(parking_data_t * dest)
{
    pthread_mutex_lock(&data_mutex);
    memcpy(dest, &parking_data, sizeof(parking_data_t));
    pthread_mutex_unlock(&data_mutex);
}

// 更新停车场数据（线程安全）
void update_parking_data(parking_data_t * new_data)
{
    pthread_mutex_lock(&data_mutex);
    memcpy(&parking_data, new_data, sizeof(parking_data_t));
    pthread_mutex_unlock(&data_mutex);

    // 通知UI更新
    if(ui_update_callback) {
        ui_update_callback(new_data);
    }
}

// 生成模拟停车场数据（基于当前数据的小幅波动）
void generate_simulated_data(parking_data_t * data)
{
    static int counter = 0;

    // 首先复制当前数据
    get_parking_data(data);

    // 基于当前数据生成小幅波动
    data->available_spaces = parking_data.available_spaces + (rand() % 11 - 5); // ±5波动
    if(data->available_spaces < 0) data->available_spaces = 0;
    if(data->available_spaces > data->total_spaces) data->available_spaces = data->total_spaces;

    data->occupied_spaces = data->total_spaces - data->available_spaces;
    data->temperature     = parking_data.temperature + (rand() % 5 - 2);    // ±2度波动
    data->humidity        = parking_data.humidity + (rand() % 11 - 5);      // ±5%湿度波动
    data->light_level     = parking_data.light_level + (rand() % 101 - 50); // ±50光照波动

    // 每小时增加一些进出场车辆
    if(counter % 12 == 0) { // 每12次（1分钟）增加一些车辆
        data->vehicles_in  = parking_data.vehicles_in + (rand() % 5 + 1);
        data->vehicles_out = parking_data.vehicles_out + (rand() % 5 + 1);
    } else {
        data->vehicles_in  = parking_data.vehicles_in;
        data->vehicles_out = parking_data.vehicles_out;
    }

    data->timestamp = time(NULL);
    counter++;

    // 调试输出
    printf("Generated data: total=%d, available=%d, occupied=%d\n", data->total_spaces, data->available_spaces,
           data->occupied_spaces);
}

char * serialize_parking_data(const parking_data_t * data)
{
    static char json_buffer[BUFFER_SIZE];

    // 添加调试信息
    printf("Serializing data - total: %d, occupied: %d\n", data->total_spaces, data->occupied_spaces);

    snprintf(json_buffer, sizeof(json_buffer),
             "{\"device_id\":\"gec6818_parking_001\","
             "\"timestamp\":%ld,"
             "\"total_spaces\":%d,"
             "\"available_spaces\":%d,"
             "\"occupied_spaces\":%d,"
             "\"temperature\":%d,"
             "\"humidity\":%d,"
             "\"light_level\":%d,"
             "\"vehicles_in\":%d,"
             "\"vehicles_out\":%d,"
             "\"status\":\"normal\"}",
             data->timestamp, data->total_spaces, data->available_spaces, data->occupied_spaces, data->temperature,
             data->humidity, data->light_level, data->vehicles_in, data->vehicles_out);

    return json_buffer;
}

// TCP连接和重连函数
int connect_to_server()
{
    struct sockaddr_in server_addr;

    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(socket_fd < 0) {
        printf("socket creation failed\n");
        return -1;
    }

    server_addr.sin_family      = AF_INET;
    server_addr.sin_port        = htons(SERVER_PORT);
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);

    if(connect(socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        printf("connect to server failed\n");
        close(socket_fd);
        socket_fd = -1;
        return -1;
    }

    printf("Connected to server [%s:%d]\n", SERVER_IP, SERVER_PORT);
    return 0;
}

// 接收服务器响应的线程
void * receive_thread(void * arg)
{
    char buffer[BUFFER_SIZE];

    while(running) {
        if(socket_fd >= 0) {
            ssize_t bytes_read = recv(socket_fd, buffer, BUFFER_SIZE - 1, 0);
            if(bytes_read > 0) {
                buffer[bytes_read] = '\0';
                printf("Server response: %s\n", buffer);

                // 这里可以解析服务器命令并更新UI
                // 例如：{"command":"refresh", "interval":5000}
            } else if(bytes_read == 0) {
                printf("Server disconnected\n");
                break;
            }
        }
        usleep(100000); // 100ms
    }
    return NULL;
}

// TCP客户端主线程函数
void * tcp_client_thread(void * arg)
{
    int ret;
    parking_data_t send_data;
    pthread_t recv_thread;

    printf("TCP Client Thread Starting...\n");

    // 连接服务器
    if(connect_to_server() != 0) {
        printf("Initial connection failed, will retry...\n");
    }

    // 启动接收线程
    if(pthread_create(&recv_thread, NULL, receive_thread, NULL) != 0) {
        printf("Failed to create receive thread\n");
        return NULL;
    }

    int send_count = 0;
    while(running) {
        // 检查连接状态
        if(socket_fd < 0) {
            printf("Attempting to reconnect...\n");
            if(connect_to_server() != 0) {
                sleep(2); // 等待2秒后重试
                continue;
            }
        }

        // 生成模拟数据
        generate_simulated_data(&send_data);

        // 调试：打印生成的数据
        printf("Before serialization - total: %d, occupied: %d\n", 
               send_data.total_spaces, send_data.occupied_spaces);

        // 序列化并发送数据
        char * json_data = serialize_parking_data(&send_data);

        printf("JSON to send: %s\n", json_data);  // 调试输出

        ret = send(socket_fd, json_data, strlen(json_data), 0);
        if(ret > 0) {
            printf("[%d] Sent to server: %s\n", send_count, json_data);
            send_count++;

            // 更新全局数据（用于UI显示）
            update_parking_data(&send_data);
        } else {
            printf("Send failed, connection may be lost\n");
            close(socket_fd);
            socket_fd = -1;
        }

        sleep(5); // 每5秒发送一次数据
    }

    // 清理资源
    if(socket_fd >= 0) {
        close(socket_fd);
    }

    pthread_join(recv_thread, NULL);
    printf("TCP Client Thread Stopped\n");

    return NULL;
}

// 启动TCP客户端线程
void start_tcp_client()
{
    if(pthread_create(&tcp_thread, NULL, tcp_client_thread, NULL) != 0) {
        printf("Failed to create TCP client thread\n");
        return;
    }
    printf("TCP Client Thread Started\n");
}

// 停止所有线程
void stop_all_threads()
{
    running = 0;
    if(socket_fd >= 0) {
        close(socket_fd);
    }
    pthread_join(tcp_thread, NULL);
    pthread_mutex_destroy(&data_mutex);
}